package common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

/**
 * 
 * @author xijiang
 * @since 2011.12.26
 * @version 1.0
 *
 */

public class CommonUtil {
	
	private final static String POST_METHOD = "POST";
	private final static String GET_METHOD = "GET";
	private final static String DEFAULT_METHOD = GET_METHOD;
	
	/**
	 * @param url the requested url
	 * @return the content of the page with that url
	 * @throws MalformedURLException 
	 */
	public static String getNumber(String urlStr) {
		if(!checkURL(urlStr)) {
			System.out.println("URL is illegal, please check for yourself!");
			return null;
		}
		
		String rn = null;//the requested number string
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = null;
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod(DEFAULT_METHOD);
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				if(line.startsWith("<TD BGCOLOR=WHITE>")) {
					rn = line.substring((18), line.indexOf("</"));
					break;
				}
			}
		} catch (MalformedURLException e) {
			System.out.println("The url is illegal!");
		} catch(IOException e) {
			System.out.println("Detect io exceptions!");
		}
		
		return rn;
	}
	
	/**
	 * check whether the requested url is legal(or validate)
	 * @param url
	 * @return true if legal, else false
	 */
	private static boolean checkURL(String urlStr) {
		boolean isValid = true;
		try {
			new URL(urlStr);
		} catch (MalformedURLException e) {
			isValid = false;
		}
		
		return isValid;
	}
	
	/**
	 * Get today's date
	 * @return
	 */
	public static Date getTodate() {
		
		return null;
	}
	
	//other static methods
	
}
